package com.xxkj.drugtraceability.ui.hascollected

import android.app.DatePickerDialog
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.xxhis.drugtraceability.base.BaseFragment
import com.xxhis.refactor.ext.dp2px
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMFragment
import com.xxkj.drugtraceability.bean.OneOutRequest
import com.xxkj.drugtraceability.bean.OneRequest
import com.xxkj.drugtraceability.databinding.FragmentOneBinding
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.ui.drugoutscan.DrugOutScanActivity
import com.xxkj.drugtraceability.ui.drugscan.DrugScanActivity
import com.xxkj.drugtraceability.utils.toast
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import java.util.*

/**
 * author: zhoujingjin
 * created on: 2024/9/18 16:51
 * description:
 */
class OneFragment:BaseVMFragment<FragmentOneBinding>(R.layout.fragment_one) {
    val viewModel by sharedViewModel<HasCollectedViewModel>()
    var page = 1
    var tradeType = "1"
    lateinit var linearLayoutManager: LinearLayoutManager
    lateinit var linearLayoutManager1: LinearLayoutManager
    lateinit var oneAdapter: OneAdapter
    lateinit var oneOutAdapter: OneOutAdapter
    companion object {
        fun newInstance(): OneFragment {
            val fragment = OneFragment()
            return fragment
        }
    }
    override fun initView() {
        binding.apply {
            linearLayoutManager =  LinearLayoutManager(requireContext())
            linearLayoutManager1 =  LinearLayoutManager(requireContext())
            recyclerView.layoutManager = linearLayoutManager
            recyclerViewOut.layoutManager = linearLayoutManager1
            oneAdapter = OneAdapter{
                startActivityForResult(
                    Intent(requireContext(), DrugScanActivity::class.java).putExtra("data",
                    it).putExtra("hasData",false),22229)
            }
            oneOutAdapter = OneOutAdapter{
                startActivityForResult(Intent(requireContext(), DrugOutScanActivity::class.java).putExtra("data",
                    it).putExtra("hasData",false),22229)
            }
            recyclerView.adapter = oneAdapter
            recyclerViewOut.adapter = oneOutAdapter
            recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener(){
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    // Get total item count
                    if (viewModel.hasMore){
                        val totalItemCount = linearLayoutManager.itemCount
                        // Get the last visible item position
                        val lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition()
                        // Threshold: how many items from the bottom should trigger data load
                        val loadMoreThreshold = 2
                        // Check if we are close enough to the end of the list
                        if (totalItemCount <= lastVisibleItemPosition + loadMoreThreshold) {
                            page++
                            viewModel.queryInStorageInfo(Gson().toJson(OneRequest(endDate,startDate,inStorageNo = binding.etInput.toString(),pageNum = page)))
                        }
                    }
                }
            })
            recyclerViewOut.addOnScrollListener(object: RecyclerView.OnScrollListener(){
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    // Get total item count
                    if (viewModel.hasMore){
                        val totalItemCount = linearLayoutManager1.itemCount
                        // Get the last visible item position
                        val lastVisibleItemPosition = linearLayoutManager1.findLastVisibleItemPosition()
                        // Threshold: how many items from the bottom should trigger data load
                        val loadMoreThreshold = 2
                        // Check if we are close enough to the end of the list
                        if (totalItemCount <= lastVisibleItemPosition + loadMoreThreshold) {
                            page++
                            viewModel.getDrugOutDepotList(Gson().toJson(OneOutRequest(endDate,startDate,outDepotNo = binding.etInput.toString(),pageNum = page)))
//                            viewModel.getPatientList(binding.etInput.text.toString())
                        }
                    }
                }
            })
            flDepart.clickN {
                showPopupWindow(flDepart)
            }
            etInput.addTextChangedListener(object :TextWatcher{
                override fun afterTextChanged(s: Editable?) {
                    if (tradeType=="1"){
                        viewModel.queryInStorageInfo(Gson().toJson(OneRequest(endDate,startDate,inStorageNo = s.toString())))
                    }else{
                        viewModel.getDrugOutDepotList(Gson().toJson(OneOutRequest(endDate,startDate,outDepotNo = s.toString())))
                    }
                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }
            })
        }

    }

    override fun initData() {
        setNowDate()
        viewModel.queryInStorageInfo(Gson().toJson(OneRequest(endDate,startDate,inStorageNo = binding.etInput.text.toString())))
    }

    override fun startObserve() {
        viewModel.oneList.observe(this, Observer {
            if (it.isEmpty()){
                oneAdapter.setEmptyView(R.layout.layout_nodata)
            }
            oneAdapter.setList(it)
        })
        viewModel.oneOutList.observe(this, Observer {
            if (it.isEmpty()){
                oneOutAdapter.setEmptyView(R.layout.layout_nodata)
            }
            oneOutAdapter.setList(it)
        })
    }
    private fun showPopupWindow(anchorView: View) {
        // 获取 PopupWindow 的布局
        val popupView = LayoutInflater.from(requireContext()).inflate(R.layout.popup_layout, null)

        // 创建 PopupWindow 对象
        val popupWindow = PopupWindow(
            popupView,
            requireActivity().dp2px(150),
            LinearLayout.LayoutParams.WRAP_CONTENT,
            true // 点击外部是否关闭 PopupWindow
        )

        // 设置背景和点击外部可关闭
//        popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.popup_background))
        popupWindow.isOutsideTouchable = true

        // 获取布局中的组件，设置监听器等
        val tv1 = popupView.findViewById<TextView>(R.id.tv_1)
        val tv2 = popupView.findViewById<TextView>(R.id.tv_2)
        tv1.clickN {
            if (tradeType!="1"){
                tradeType = "1"
                binding.recyclerView.visibility = View.VISIBLE
                binding.recyclerViewOut.visibility = View.GONE
                binding.tvDepart.text = "入库采集"
                viewModel.hasMore = true
                page=1
                viewModel.queryInStorageInfo(Gson().toJson(OneRequest(endDate,startDate,inStorageNo = binding.etInput.text.toString())))
            }
            popupWindow.dismiss()

        }
        tv2.clickN {
            if (tradeType!="2"){
                tradeType = "2"
                binding.recyclerView.visibility = View.GONE
                binding.recyclerViewOut.visibility = View.VISIBLE
                binding.tvDepart.text = "出库采集"
                viewModel.hasMore = true
                page=1
                viewModel.getDrugOutDepotList(Gson().toJson(OneOutRequest(endDate,startDate,outDepotNo = binding.etInput.text.toString())))
            }
            popupWindow.dismiss()
        }
        // 显示 PopupWindow
        popupWindow.showAsDropDown(anchorView, 0, 0, Gravity.BOTTOM)
}
    private val calendarStart = Calendar.getInstance()
    private  val calendarEnd = Calendar.getInstance()
    private var startDatePicker : DatePickerDialog? = null
    private var endDatePicker : DatePickerDialog? = null
    private var startDate:String="${calendarStart.get(Calendar.YEAR)}-${calendarStart.get(
        Calendar.MONTH) + 1}-${calendarStart.get(Calendar.DAY_OF_MONTH)}"
    private var endDate:String="${calendarEnd.get(Calendar.YEAR)}-${calendarEnd.get(
        Calendar.MONTH) + 1}-${calendarEnd.get(Calendar.DAY_OF_MONTH)}"
     fun showDatePicker(){
        if (startDatePicker==null){
            startDatePicker = DatePickerDialog(
                requireContext(),
                { _, year, monthOfYear, dayOfMonth ->
                    calendarStart.set(year, monthOfYear, dayOfMonth)
                    if (endDatePicker==null){
                        endDatePicker = DatePickerDialog(
                            requireContext(),
                            { _, endYear, endMonthOfYear, endDayOfMonth ->
                                calendarEnd.set(endYear, endMonthOfYear, endDayOfMonth)
                                startDate = "${calendarStart.get(Calendar.YEAR)}-${calendarStart.get(
                                    Calendar.MONTH) + 1}-${calendarStart.get(Calendar.DAY_OF_MONTH)}"
                                endDate = "${calendarEnd.get(Calendar.YEAR)}-${calendarEnd.get(
                                    Calendar.MONTH) + 1}-${calendarEnd.get(Calendar.DAY_OF_MONTH)}"
                                viewModel.dateTime.postValue(startDate+"\n"+endDate)
                                if (tradeType=="1"){
                                    viewModel.queryInStorageInfo(Gson().toJson(OneRequest(endDate,startDate,inStorageNo = binding.etInput.text.toString())))
                                }else{
                                    viewModel.getDrugOutDepotList(Gson().toJson(OneOutRequest(endDate,startDate,outDepotNo = binding.etInput.text.toString())))
                                }
                            },
                            calendarEnd.get(Calendar.YEAR), calendarEnd.get(Calendar.MONTH), calendarEnd.get(
                                Calendar.DAY_OF_MONTH)

                        )
                    }
                    endDatePicker?.show()
                    requireActivity().toast(R.string.please_max_date)
                },
                calendarStart.get(Calendar.YEAR), calendarStart.get(Calendar.MONTH), calendarStart.get(
                    Calendar.DAY_OF_MONTH)
            )
        }
        startDatePicker?.show()
        requireActivity().toast(R.string.please_min_date)
    }
    fun setNowDate(){
        viewModel.dateTime.postValue(startDate+"\n"+endDate)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode==22229&&resultCode==3333){
            if (tradeType=="1"){
                viewModel.queryInStorageInfo(Gson().toJson(OneRequest(endDate,startDate,inStorageNo = binding.etInput.text.toString())))
            }else{
                viewModel.getDrugOutDepotList(Gson().toJson(OneOutRequest(endDate,startDate,outDepotNo = binding.etInput.text.toString())))
            }}
    }
}